﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Clarius.PresentationModel
{
	public static class EnumerableExtensions
	{
		public static IEnumerable<T> ForEach<T>(this IEnumerable<T> source, Action<T> action)
		{
			foreach (var item in source)
			{
				action(item);
				yield return item;
			}
		}

		public static IsEmptyEnumerator<T> ToIsEmpty<T>(this IEnumerable<T> values)
		{
			return new IsEmptyEnumerator<T>(values);
		}
	}

	public class IsEmptyEnumerator<T> : IEnumerable<T>, IEnumerator<T>
	{
		string originalValues;
		IEnumerator<T> values;
		bool initial = true;
		bool isEmpty;

		public IsEmptyEnumerator(IEnumerable<T> values)
		{
			originalValues = values.ToString();
			this.values = values.GetEnumerator();
			isEmpty = !this.values.MoveNext();
		}

		public bool IsEmpty
		{
			get { return isEmpty; }
		}

		IEnumerator<T> IEnumerable<T>.GetEnumerator()
		{
			return this;
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return this;
		}

		T IEnumerator<T>.Current
		{
			get { return initial ? default(T) : values.Current; }
		}

		void IDisposable.Dispose()
		{
			values.Dispose();
		}

		object IEnumerator.Current
		{
			get { return ((IEnumerator<T>)this).Current; }
		}

		bool IEnumerator.MoveNext()
		{
			bool result = initial ? !isEmpty : values.MoveNext();
			initial = false;

			return result;
		}

		void IEnumerator.Reset()
		{
			values.Reset();
		}

		public override string ToString()
		{
			return originalValues;
		}
	}
}
